package com.example.data0306.base;

import android.util.SparseArray;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseVpAdapter<T> extends FragmentPagerAdapter {
    private final SparseArray<Fragment> mFragmentCache;
    private List<T> mData;

    public BaseVpAdapter(@NonNull FragmentManager fm) {
        super(fm);
        mFragmentCache = new SparseArray<>();
        mData = new ArrayList<>();
    }


    @NonNull
    @Override
    public Fragment getItem(int position) {
        Fragment fragment = mFragmentCache.get(position);
        if (fragment == null) {
            fragment = createFragment(position);
            mFragmentCache.put(position, fragment);
        }
        return fragment;
    }

    protected abstract Fragment createFragment(int position);

    public void addData(T data) {
        mData.add(data);
        notifyDataSetChanged();
    }

    public void addData(List<T> datas) {
        mData.addAll(datas);
        notifyDataSetChanged();
    }

    protected T getData(int position) {
        return mData.get(position);
    }

    @Override
    public int getCount() {
        return mData.size();
    }
}
